<template>
  <div class="admin-posts-page">
    <div class="header-section">
      <h1 class="page-title">社区动态管理</h1>
      <div class="search-filter-bar">
        <input
            v-model="searchQuery"
            type="text"
            placeholder="搜索帖子ID或发帖人..."
            class="search-input"
            @input="handleSearch"
        />
        <select v-model="activeStatus" class="status-select" @change="handleFilter">
          <option value="all">所有状态</option>
          <option :value="2">待审核</option>
          <option :value="1">正常</option>
          <option :value="3">已下架</option>
        </select>
        <select v-model="activeType" class="type-select" @change="handleFilter">
          <option value="all">所有类型</option>
          <option :value="3">求助帖</option>
          <option :value="2">讨论帖</option>
        </select>

      </div>
    </div>

    <div class="posts-table-container">
      <table class="posts-table">
        <thead>
        <tr>
          <th>帖子ID</th>
          <th>发帖人</th>
          <th>内容摘要</th>
          <th>类型</th>
          <th>点赞数</th>
          <th>评论数</th>
          <th>发布日期</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody v-if="isLoading">
        <tr>
          <td colspan="9" class="empty-state">
            <i class="fas fa-spinner fa-spin"></i>
            <p>正在加载数据...</p>
          </td>
        </tr>
        </tbody>
        <tbody v-else-if="posts.length > 0">
        <tr v-for="post in posts" :key="post.postId">
          <td class="post-id">{{ post.postId }}</td>
          <td>{{ post.user.nickname }}</td>
          <td class="content-summary">
            {{ post.title }}
          </td>
          <td>
              <span class="type-badge" :class="typeClass(post.type)">
                {{ getTypeName(post.type) }}
              </span>
          </td>
          <td>{{ post.likeCount }}</td>
          <td>{{ post.replyCount }}</td>
          <td>{{ formatDate(post.createdAt) }}</td>
          <td>
              <span class="status-badge" :class="statusClass(post.status)">
                {{ getStatusName(post.status) }}
              </span>
          </td>
          <td>
            <button class="action-btn btn-view" @click="showDetailsModal(post)">
              查看详情
            </button>
            <button
                v-if="post.status === 2"
                class="action-btn btn-approve"
                @click="confirmAction('approve', post)"
            >
              审核通过
            </button>
            <button
                v-if="post.status === 1"
                class="action-btn btn-hide"
                @click="confirmAction('hide', post)"
            >
              下架
            </button>
            <button
                v-if="post.status === 3"
                class="action-btn btn-recover"
                @click="confirmAction('recover', post)"
            >
              恢复
            </button>
            <button class="action-btn btn-delete" @click="confirmAction('delete', post)">
              删除
            </button>
          </td>
        </tr>
        </tbody>
        <tbody v-else>
        <tr>
          <td colspan="9" class="empty-state">
            <i class="fas fa-box-open empty-icon"></i>
            <p>暂无相关帖子</p>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <Pagination
        v-if="!isLoading && totalPages > 0"
        :current-page="currentPage"
        :total-pages="totalPages"
        @page-changed="handlePageChange"
    />

    <AppModal :visible="detailsModalVisible" title="帖子详情" @update:visible="detailsModalVisible = $event">
      <div v-if="selectedPost" class="modal-content-details">
        <h3>用户名: {{ selectedPost.user.nickname }}</h3>
        <p class="post-date">{{ formatDate(selectedPost.createdAt) }}</p>
        <div class="post-content">{{ selectedPost.content }}</div>

        <div v-if="parsedImages.length > 0" class="post-images">
          <img
              v-for="(image, index) in parsedImages"
              :key="index"
              :src="image"
              alt="帖子图片"
              class="post-image"
          />
        </div>

        <div class="post-stats">
          <span>点赞数:<i class="fas fa-thumbs-up"></i> {{ selectedPost.likeCount }}</span>
          <span>评论数:<i class="fas fa-comment"></i> {{ selectedPost.replyCount }}</span>
          <span>收藏数:<i class="fas fa-star"></i> {{ selectedPost.collectCount }}</span>
        </div>
      </div>
    </AppModal>

    <AppModal
        :visible="confirmModalVisible"
        :title="actionTitle"
        @update:visible="confirmModalVisible = $event"
        @confirm="executeAction"
    >
      <div class="modal-content-confirm">
        <p>您确定要**{{ actionText }}**吗？此操作不可逆。</p>
      </div>
    </AppModal>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import Pagination from '../components/Pagination.vue';
import AppModal from '../components/AppModal.vue';
import axios from 'axios';
import { useRoute } from 'vue-router'; // 引入 useRoute


// 状态管理
const posts = ref([]);
const totalPages = ref(0);
const detailsModalVisible = ref(false);
const confirmModalVisible = ref(false);
const selectedPost = ref(null);
const searchQuery = ref('');
const activeStatus = ref('all');
const activeType = ref('all');
const activeIsHot = ref(undefined);
const currentPage = ref(1);
const isLoading = ref(false);
const pageSize = 5;
const actionType = ref('');
const actionTitle = ref('');
const actionText = ref('');

// 状态名称映射 (新增已下架状态)
const statusMap = {
  all: '所有状态',
  2: '待审核',
  1: '正常',
  3: '已下架',
};

// 类型名称映射
const typeMap = {
  all: '所有类型',
  3: '求助帖',
  2: '讨论帖',
};

// 工具函数
const getStatusName = (status) => statusMap[status] || status;
const getTypeName = (type) => typeMap[type] || type;
const statusClass = (status) => `status-${status}`;
const typeClass = (type) => `type-${type}`;
const formatDate = (dateString) => {
  if (!dateString) return 'N/A';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: 'numeric',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
};

// 后端数据请求函数
const fetchPosts = async () => {
  isLoading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize,
      status: activeStatus.value === 'all' ? undefined : activeStatus.value,
      type: activeType.value === 'all' ? undefined : activeType.value,
      isHot: activeIsHot.value,
    };

    // 检查 searchQuery 是否是纯数字
    const isPostId = /^\d+$/.test(searchQuery.value);
    if (isPostId) {
      params.postId = parseInt(searchQuery.value, 10);
      params.nickname = undefined;
    } else {
      params.nickname = searchQuery.value || undefined;
      params.postId = undefined;
    }

    const response = await axios.get('/api/posts', { params });
    const responseData = response.data;
    console.log(responseData)
    if (responseData && responseData.data && responseData.data.records) {
      posts.value = responseData.data.records;
      // 修正：确保总页数至少为1，以防后端返回0但有记录
      totalPages.value = Math.max(1, responseData.data.pages);
    } else if(!responseData.data) {
    posts.value = responseData.records;
    totalPages.value = Math.max(1, responseData.pages);
  } else {
      posts.value = [];
      totalPages.value = 0;
      console.warn('后端返回的数据格式不符合预期:', responseData);
  }
  } catch (error) {
    console.error('获取帖子列表失败:', error);
    posts.value = [];
    totalPages.value = 0;
  } finally {
    isLoading.value = false;
  }
};

// 新增：安全解析图片JSON的计算属性
const parsedImages = computed(() => {
  if (selectedPost.value && selectedPost.value.images) {
    try {
      // 确保 images 字符串不是 "null" 或者空字符串
      const imagesString = selectedPost.value.images.trim();
      if (imagesString && imagesString !== 'null') {
        const parsed = JSON.parse(imagesString);
        // 确保解析结果是数组
        return Array.isArray(parsed) ? parsed : [];
      }
    } catch (e) {
      console.error('解析图片JSON失败:', e);
    }
  }
  return [];
});

// 事件处理
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchPosts();
};

const handleSearch = () => {
  currentPage.value = 1;
  fetchPosts();
};

const handleFilter = () => {
  currentPage.value = 1;
  fetchPosts();
};

const showDetailsModal = async (post) => {
  try {
    const response = await axios.get(`/api/posts/${post.postId}`);
    if (response && response.data && response.data.data) {
      selectedPost.value = response.data.data;
    }else{
      selectedPost.value = response.data;
    }
    detailsModalVisible.value = true;
  } catch (error) {
    console.error('获取帖子详情失败:', error);
  }
};

const confirmAction = (type, post) => {
  selectedPost.value = post;
  actionType.value = type;
  if (type === 'approve') {
    actionTitle.value = '审核通过';
    actionText.value = '审核通过此帖子，使其变为正常状态';
  } else if (type === 'hide') {
    actionTitle.value = '下架帖子';
    actionText.value = '下架此帖子，使其变为已下架状态';
  } else if (type === 'recover') {
    actionTitle.value = '恢复帖子';
    actionText.value = '恢复此帖子，使其变为正常状态';
  } else if (type === 'delete') {
    actionTitle.value = '删除帖子';
    actionText.value = '永久删除此帖子';
  }
  confirmModalVisible.value = true;
};

const executeAction = async () => {
  if (!selectedPost.value) return;

  try {
    const postId = selectedPost.value.postId;
    if (actionType.value === 'approve') {
      await axios.put(`/api/posts/${postId}/status`, null, {params: {status: 1}});
      console.log(`帖子 ${postId} 已被审核通过。`);
    } else if (actionType.value === 'hide') {
      await axios.put(`/api/posts/${postId}/status`, null, {params: {status: 3}});
      console.log(`帖子 ${postId} 已被下架。`);
    } else if (actionType.value === 'recover') {
      await axios.put(`/api/posts/${postId}/status`, null, {params: {status: 1}});
      console.log(`帖子 ${postId} 已被恢复。`);
    } else if (actionType.value === 'delete') {
      await axios.delete(`/api/posts/${postId}`);
      console.log(`帖子 ${postId} 已被删除。`);
    }
  } catch (error) {
    console.error('执行操作失败:', error);
  } finally {
    confirmModalVisible.value = false;
    fetchPosts();
  }
};

onMounted(() => {
  fetchPosts();

});
</script>

<style scoped>
/* 页面布局 */
.admin-posts-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.search-filter-bar {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
}

.search-input,
.status-select,
.type-select,
.is-hot-select {
  padding: 8px 12px;
  border: 1px solid #e0e6ed;
  border-radius: 6px;
  font-size: 13px;
  transition: all 0.3s;
  background-color: white;
  min-width: 120px;
}

.search-input:focus,
.status-select:focus,
.type-select:focus,
.is-hot-select:focus {
  outline: none;
  border-color: #4e54c8;
  box-shadow: 0 0 0 3px rgba(78, 84, 200, 0.1);
}

.posts-table-container {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  overflow-x: auto;
  margin-bottom: 20px;
}

.posts-table {
  width: 100%;
  border-collapse: collapse;
}

.posts-table th,
.posts-table td {
  padding: 12px 10px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
  font-size: 13px;
  vertical-align: middle;
}

.posts-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #555;
  text-transform: uppercase;
}

.posts-table td {
  color: #666;
}

/* 列宽优化 */
.posts-table tr th:nth-child(1),
.posts-table tr td:nth-child(1) {
  width: 5%;
  min-width: 60px;
}

.posts-table tr th:nth-child(2),
.posts-table tr td:nth-child(2) {
  width: 8%;
  min-width: 80px;
}

.posts-table tr th:nth-child(3),
.posts-table tr td:nth-child(3) {
  width: 28%;
  min-width: 250px;
}

.posts-table tr th:nth-child(4),
.posts-table tr td:nth-child(4) {
  width: 8%;
  min-width: 80px;
}

.posts-table tr th:nth-child(5),
.posts-table tr td:nth-child(5),
.posts-table tr th:nth-child(6),
.posts-table tr td:nth-child(6) {
  width: 7%;
  min-width: 60px;
  text-align: center;
}

.posts-table tr th:nth-child(7),
.posts-table tr td:nth-child(7) {
  width: 12%;
  min-width: 120px;
}

.posts-table tr th:nth-child(8),
.posts-table tr td:nth-child(8) {
  width: 7%;
  min-width: 80px;
}

.posts-table tr th:nth-child(9),
.posts-table tr td:nth-child(9) {
  width: 18%;
  min-width: 180px;
}

.post-id {
  font-family: monospace;
}

.content-summary {

  align-items: center; /* 垂直居中对齐 */
  /* 让文字部分自动占据剩余空间 */
  min-width: 0;
}

.content-summary span {
  /* 确保热门标签不被压缩 */
  flex-shrink: 0;
}

.status-badge, .type-badge, .is-hot-badge {
  padding: 4px 8px;
  border-radius: 16px;
  font-size: 11px;
  font-weight: 600;
  color: white;
  white-space: nowrap;
  display: inline-block;
}

/* 状态和类型颜色 */
.status-2 {
  background-color: #f39c12;
}

.status-1 {
  background-color: #27ae60;
}

.status-3 {
  background-color: #7f8c8d;
}

.type-3 {
  background-color: #3498db;
}

.type-2 {
  background-color: #9b59b6;
}

/* 热门类型样式 */
.is-hot-badge {
  background-color: #e74c3c;
  flex-shrink: 0;
}

.action-btn {
  padding: 6px 10px;
  border-radius: 4px;
  border: none;
  font-size: 11px;
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 5px;
  margin-bottom: 5px;
  font-weight: 500;
  white-space: nowrap;
}

.btn-view {
  background-color: #5d67e8;
  color: white;
}

.btn-approve {
  background-color: #46c11d;
  color: white;
  font-weight: 600;
}

.btn-hide {
  background-color: #e67e22;
  color: white;
}

.btn-delete {
  background-color: #e74c3c;
  color: white;
}

.btn-recover {
  background-color: #3498db;
  color: white;
}

.action-btn:hover {
  opacity: 0.9;
}

.empty-state {
  text-align: center;
  padding: 30px;
  color: #999;
}

.empty-icon {
  font-size: 36px;
  margin-bottom: 8px;
}

/* 模态框样式 */
.modal-content-details {
  line-height: 1.6;
}

.modal-content-details h3 {
  font-size: 17px;
  font-weight: 600;
  margin-bottom: 5px;
}

.post-date {
  font-size: 12px;
  color: #888;
  margin-bottom: 15px;
}

.post-content {
  font-size: 14px;
  color: #444;
  margin-bottom: 20px;
  white-space: pre-wrap;
}

/* 图片容器样式 */
.post-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 15px;
  margin-bottom: 20px;
}

.post-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid #ddd;
}

.post-stats {
  display: flex;
  gap: 20px;
}

.post-stats span {
  font-size: 13px;
  color: #666;
  display: flex;
  align-items: center;
}

.post-stats .fa-heart {
  color: #e74c3c; /* 红色爱心 */
}

.post-stats i {
  margin-right: 5px;
  color: #888;
}

.modal-content-confirm {
  text-align: center;
  padding: 20px 0;
}

.modal-content-confirm p {
  font-size: 15px;
}

.modal-content-confirm strong {
  color: #e74c3c;
}
</style>